#include "ThreadPool.hpp"
#include "Task.hpp"
#include "TaskQue.hpp"
#include <unistd.h>


namespace wd
{

ThreadPool::ThreadPool(int num,size_t cap)
    :_threadNum(num)
     ,_taskCapacity(cap)
     ,_taskque(_taskCapacity)
     ,_isRunning(false)    
    {
        _threadPool.reserve(cap);
    }

void ThreadPool::start(){
    _isRunning = true;
    for(int i =0;i<_threadNum;i++){
        _threadPool.emplace_back(thread(&ThreadPool::doTask,this));
    }
}

void ThreadPool::stop(){
    while(!_taskque.empty()){
        sleep(1);
    }

    _isRunning = false;
    _taskque.wakeup();

    for(auto &it:_threadPool){
        it.join(); 
    }
}

void ThreadPool::addTask(TaskPtr task){
    if(task && _isRunning){
    _taskque.push(task);
    }
}

void ThreadPool::doTask(){

    while(_isRunning){
        auto task = _taskque.pop();
        if(!task){
            break;
        }
        task->process();
    }
}


}//end of namespace wa
